import e, { Request, Response, Router, urlencoded, json } from 'express';

import * as todoService from '../services/todo.service.js'
import * as accountService from '../services/account.service.js'
import { Responses } from '../utils/responses.js'
const router = Router();
//根据token，设置用户信息
router.use(async (req: Request, res: Response, next) => {
    //    //判断请求路径是否为 /account/register，/account/login，/account/logout
    //    const path = [
    //      'post /account/register',
    //      'post /account/login',
    //      'post /account/logout',
    //      'get /todos',
    //      'get /users',
    //      'get /'
    //    ]
    //    const regpath=[
    //      /\/todos\/\d/i,
    //      /\/users\/\d/i
    //    ]
    //    const test_path=`${req.method} ${req.path}`.toLocaleLowerCase()
    //    if(path.includes(req.path)){
    //      next()
    //      return
    //    }
    //    for (const reg of regpath) {
    //      if (reg.test(req.path)) {
    //        next()
    //        return
    //      }
    //    }


    const token = req.headers.authorization
    if (token) {
        const user = await accountService.getUserByToken(token)
        if (user) {
            req.body.user = user
        }
    }
    if (req.body.user) {
        next()
        return
    } else {
        res.status(401).send(Responses.error([], '未登录'));
        return
    }
})

//注销登录
router.post('/account/logout', async (req: Request, res: Response) => {
    try {
        await accountService.logout(req.body.user.id)
        res.send(Responses.success({}, '注销成功'));
    } catch (error) {
        res.status(400).send(Responses.error([], '注销异常'));
    }
})

// 账户路由
router.get('/account/', async (req: Request, res: Response) => {
    const userId = parseInt(req.body.user.id);
    const user = await accountService.getUserById(userId);
    if (user) {
        res.send(Responses.success(user, ''));
    } else {
        res.status(400).send(Responses.error([], '用户不存在'));
    }
});

// 更新User信息
router.put('/account/', async (req: Request, res: Response) => {
    const userId = parseInt(req.body.user.id);
    const { username, password, description } = req.body;
    const user = await accountService.updateUser(userId, { userName: username, password: password, description: description })
    if (user) {
        const { password, ...rest } = user
        res.send(Responses.success(rest, '更新成功'));
    } else {
        res.status(400).send(Responses.error([], '更新失败'));
    }
})

// 创建新的 todo
router.post('/todos', async (req: Request, res: Response) => {
    try {
        let { title, description = '', completed } = req.body;
        if (completed == '') {
            completed = false
        }
        completed = !!parseInt(completed)
        const todo = await todoService.createTodo({ title, description, completed, user: req.body.user })
        res.send(Responses.success(todo, '创建成功'));
    } catch (error) {
        res.status(400).send(Responses.error([], error.message));
    }

});

// 更新指定 id 的 todo
router.put('/todos/:id', async (req: Request, res: Response) => {
    try {
        let { id } = req.params;
        let { title, description, completed } = req.body;
        if (completed == '') {
            completed = false
        }
        completed = !!parseInt(completed)
        const todo = await todoService.updateTodo(parseInt(id), req.body.user.id, { title, description, completed })
        res.send(Responses.success(todo, '更新成功'));
    } catch (error) {
        res.status(400).send(Responses.error([], error.message));
    }
});

// 删除指定 id 的 todo
router.delete('/todos/:id', async (req: Request, res: Response) => {
    try {
        const { id } = req.params;
        let todo = await todoService.deleteTodo(parseInt(id), req.body.user.id)
        res.send(Responses.success(todo, '删除成功'));
    } catch (error) {
        res.status(400).send(Responses.error([], error.message));
    }
});


export default router;